package com.crm.jdy.controller.usermanager;


import com.crm.jdy.common.dto.RoleInfoDto;
import com.crm.jdy.common.dto.UserInfoDto;
import com.crm.jdy.common.pojo.RoleInfo;
import com.crm.jdy.common.pojo.UserInfo;
import com.crm.jdy.common.shiro.TokenUtil;
import com.crm.jdy.common.utils.MD5Utils;
import com.crm.jdy.common.utils.api.ResultVo;
import com.crm.jdy.common.utils.redis.RedisUtils;
import com.crm.jdy.service.usermanager.UserInfoService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.List;
import java.util.Map;

@Api(tags = "Login", description = "用户登录接口")
@RestController
@Controller
public class LoginController {

    @Reference(version = "${service.version}", check = false)
    UserInfoService callAplanInfoService;

    @Resource
    private RedisUtils redisUtil;

    @ApiOperation("您没有权限")
    @GetMapping(value = "/redisUtil")
    @ResponseBody
    public ResultVo redisUtil(){
        redisUtil.set("kong","ceshi");
        return  ResultVo.failed("您没有权限！");
    }

    @ApiOperation("您没有权限")
    @GetMapping(value = "/noAuthorize")
    @ResponseBody
    public ResultVo notRole() {
        return  ResultVo.failed("您没有权限！");
    }


    @ApiOperation("您没有登录")
    @GetMapping(value = "/nologin")
    @ResponseBody
    public ResultVo nologin() {
        return ResultVo.failed("您没有登录！");
    }

    @ApiOperation("注销接口")
    @GetMapping(value = "/logout")
    @ResponseBody
    public ResultVo  logout() {
        Subject subject = SecurityUtils.getSubject();
        //注销
        subject.logout();
        return ResultVo.success("成功注销！");
    }


    @ApiOperation("测试接口信息")
    @GetMapping(value = "/getUserDetails")
    @ResponseBody
    public ResultVo  getUserDetails() {
        UserInfoDto  userInfoDto =  callAplanInfoService.getUserDetails("测试01");
        return ResultVo.success(userInfoDto);
    }


    @ApiOperation("数据备份信息")
    @GetMapping(value = "/getUserBeifen")
    @ResponseBody
    public ResultVo  getUserBeifen() {

        String filePath="D:\\数据库文件\\";
        String dbName="crm";//备份的数据库名
        String username="root";//用户名
        String password="root";//密码
        File uploadDir = new File(filePath);
            if (!uploadDir.exists())
                    uploadDir.mkdirs();

        String cmd =  "mysqldump -u"+ username +"  -p "+password + dbName + " -r "
                + filePath + "/" + dbName+new java.util.Date().getTime()+ ".sql";
        System.out.println("-------777777---------");
        System.out.println(cmd);
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            System.out.println(process);
            System.out.println("----------------");
            System.out.println("备份数据库成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVo.success();
    }







    @ApiOperation("登录接口")
    @PostMapping(value = "/login")
    @ResponseBody
    public ResultVo login(String name, String password, HttpServletRequest request, HttpServletResponse response) {
        String ips = "";
        String token = "";
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(name, MD5Utils.inputPassToFormPass(password));
            subject.login(usernamePasswordToken);
//            UserInfo role = callAplanInfoService.getUserByName(name);
            UserInfoDto  userInfoDto =  callAplanInfoService.getUserDetails(name);
            if(null  == userInfoDto && ObjectUtils.isEmpty(userInfoDto) ){
                return ResultVo.failed("error");
            }else{
                ips  = request.getRemoteAddr();
                 if(StringUtils.isEmpty(ips) && null == ips) {
                     ips = request.getRemoteHost();
                 }
                if(StringUtils.isEmpty(ips) && null == ips) {
                    return ResultVo.failed();
                }else{
                    token = TokenUtil.getToken(userInfoDto.getUserName(), userInfoDto.getUserId(), ips);
                    return ResultVo.success(userInfoDto,token);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            return ResultVo.failed("error");
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String", paramType = "path")
    })
    @ApiOperation("验证接口")
    @GetMapping("verify/{token}")
    @ResponseBody
    public ResultVo verify(@NotNull @PathVariable String token, HttpServletRequest request){
        String ips ="";
        ips  = request.getRemoteAddr();
        if(StringUtils.isEmpty(ips) && null == ips) {
            ips = request.getRemoteHost();
        }
        if(StringUtils.isEmpty(ips) && null == ips) {
            return ResultVo.failed();
        }
        // 需要token
        Claims tokenBody = TokenUtil.getTokenBody(token,ips);
        String Id  = tokenBody.getId();
        if(null != Id &&  !StringUtils.isEmpty(Id)){
            if(callAplanInfoService.seleteVerify(Id)){
                return ResultVo.success("success");
            }else{
                return ResultVo.failed("fail");
            }
        }else{
            return ResultVo.failed("fail");
        }

    }



}
